package sy.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sy.pageModel.DataGrid;
import sy.pageModel.OrderDoctor;
import sy.pageModel.OrderTour;
import sy.service.OrderTourServiceI;
import sy.util.DateUtil;
import sy.util.StringUtil;

@Service("orderTourService")
public class OrderTourServiceImpl extends BaseService implements OrderTourServiceI {

	
	@Override
	public DataGrid datagrid(OrderTour order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_tourism_order a, view_hy b where a.userid=b.vnumber";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select a.id, userid, a.deptid, name as depts, circuit, p_count, price, ys_money, sj_money, service_detail, sq_time, s_time, state, xm, sjh, sfzh "
		      + "from xj_tourism_order a, view_hy b, p_info c where a.userid=b.vnumber and a.deptid=c.id";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderTour> orderList = new ArrayList<OrderTour>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderTour order = new OrderTour();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("id"));
                order.setCardId(rs.getString("userid"));
                order.setAgencyId(rs.getString("deptid"));
                order.setAgencyName(rs.getString("depts"));
                order.setLineName(rs.getString("circuit"));
                order.setPersonCount(rs.getInt("p_count"));
                order.setLineFee(rs.getDouble("price"));
                order.setTotalFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("service_detail"));
                order.setCreateTime(rs.getString("sq_time"));
                order.setServiceTime(rs.getString("s_time"));
                order.setStatus(rs.getString("state"));
                order.setName(rs.getString("xm"));
                order.setMobile(rs.getString("sjh"));
                order.setCid(rs.getString("sfzh"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	@Override
	public DataGrid datagridForAccepted(OrderTour order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_tourism_order a, view_hy b where a.userid=b.vnumber and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select a.id, userid, a.deptid, name as depts, circuit, p_count, price, ys_money, sj_money, service_detail, sq_time, s_time, state, xm, sjh, sfzh "
		      + "from xj_tourism_order a, view_hy b, p_info c where a.userid=b.vnumber and a.deptid=c.id and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderTour> orderList = new ArrayList<OrderTour>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderTour order = new OrderTour();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("id"));
                order.setCardId(rs.getString("userid"));
                order.setAgencyId(rs.getString("deptid"));
                order.setAgencyName(rs.getString("depts"));
                order.setLineName(rs.getString("circuit"));
                order.setPersonCount(rs.getInt("p_count"));
                order.setLineFee(rs.getDouble("price"));
                order.setTotalFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("service_detail"));
                order.setCreateTime(rs.getString("sq_time"));
                order.setServiceTime(rs.getString("s_time"));
                order.setStatus(rs.getString("state"));
                order.setName(rs.getString("xm"));
                order.setMobile(rs.getString("sjh"));
                order.setCid(rs.getString("sfzh"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	private String addWhere(OrderTour order, String sql) {
		if(!StringUtil.isNullOrEmpty(order.getOrderId())) {
			sql += " and a.id like '%" + order.getOrderId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCardId())) {
			sql += " and userid like '%" + order.getCardId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getName())) {
			sql += " and xm like '%" + order.getName() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getMobile())) {
			sql += " and sjh like '%" + order.getMobile() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeStart())) {
			sql += " and sq_time >= '" + order.getCreateTimeStart() + "'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeEnd())) {
			sql += " and sq_time <= '" + order.getCreateTimeEnd() + "'";
		}
		return sql;
	}
	
	private String addLimit(OrderTour order, String sql) {
		int fromRow = (order.getPage() - 1) * order.getRows();
	    sql += " limit " + fromRow + "," + order.getRows();
	    return sql;
	}
	
	private String addOrderBy(OrderTour order, String sql) {
		if (order.getSort() != null) {
			if("cardId".equals(order.getSort())) {
				order.setSort("userid");
			} else if("name".equals(order.getSort())) {
				order.setSort("convert(xm using gbk)");
			} else if("createTime".equals(order.getSort())) {
				order.setSort("sq_time");
			} else if("mobile".equals(order.getSort())) {
				order.setSort("sjh");
			} else if("orderId".equals(order.getSort())) {
				order.setSort("id");
			} else if("statusName".equals(order.getSort())) {
				order.setSort("state");
			} else if("cid".equals(order.getSort())) {
				order.setSort("sfzh");
			} else if("agencyName".equals(order.getSort())) {
				order.setSort("convert(depts using gbk)");
			} else if("lineName".equals(order.getSort())) {
				order.setSort("convert(circuit using gbk)");
			} else if("serviceTime".equals(order.getSort())) {
				order.setSort("s_time");
			} else if("personCount".equals(order.getSort())) {
				order.setSort("p_count");
			} else if("lineFee".equals(order.getSort())) {
				order.setSort("price");
			} else if("totalFee".equals(order.getSort())) {
				order.setSort("ys_money");
			}
			sql += " order by " + order.getSort() + " " + order.getOrder();
		}
		return sql;
	}
	
	@Override
	@Transactional
	public OrderTour add(OrderTour order) throws Exception {
		System.out.println(order);
	    //得到线路价钱等信息
	    Map<String, Object> infoMap = getLineInfo(order.getLineId());
	    if(infoMap.isEmpty()) {
	    	throw new Exception("获取线路信息失败！");
	    }
	    order.setLineName((String)infoMap.get("lineName"));
	    order.setLineFee((Double)infoMap.get("price"));
	    order.setTotalFee(order.getLineFee() * order.getPersonCount());
	    order.setStatus(OrderDoctor.ORDER_STATUS_ID_WAIT_ACCEPT);
	    
	    Date now = new Date();
	    order.setCreateTime(DateUtil.format(now));
	    String orderId = "LY-" + order.getCardId() + "-" + DateUtil.format(now, "yyyyMMddHHmmss");
	    order.setOrderId(orderId);
	    order.setId(orderId);
	    
	    System.out.println(order);
	    
	    String sql = "insert into xj_tourism_order (id,circuit,price,p_count,s_time,sq_time,ys_money,state,userid,deptid) " + 
	             "values(?,?,?,?,?,?,?,?,?,?)";
	
		Object[] paras = new Object[] {
				  order.getId(),
				  order.getLineName(),
				  order.getLineFee(),
				  order.getPersonCount(),
				  order.getServiceTime(),
				  order.getCreateTime(),
				  order.getTotalFee(),
				  order.getStatus(),
				  order.getCardId(),
				  order.getAgencyId()
		};
		
		int affectRow = 0;
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
	
	    return order;
	}

	@Override
	@Transactional
	public OrderTour addDetails(OrderTour order) throws Exception {
		int affectRow = 0;
		String sql = "update xj_tourism_order set sj_money=?,service_detail=?,state=?" 
		             + " where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getOrderId()
		};
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("生成详单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("订单记录不存在！");
		} else if(affectRow > 1) {
			throw new RuntimeException("存在多条订单记录，生成详单失败，请联系系统管理员！");
		}
		return order;
	}

	@Override
	@Transactional
	public OrderTour edit(OrderTour order) throws Exception {
		String sql = "update xj_tourism_order set sj_money=?,service_detail=?,state=?  where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
				order.getActualFee(),
				order.getServiceDetails(),
				order.getStatus(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		updateMenber(order.getCardId(),order.getOrderId(),order.getActualFee(),order.getStatus());
		return order;
	}
	@Override
	public OrderTour saveTour(OrderTour order) {
		String sql = "update xj_tourism_order set sj_money=?,service_detail=? where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				order.getActualFee(),
				order.getServiceDetails(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	public OrderTour editStayStatus(OrderTour order) {
		String sql = "update xj_tourism_order set state=? where id=?";
		System.out.println(sql);
		order.setStatus(OrderDoctor.ORDER_STATUS_ID_CANCELLED);
		Object[] paras = new Object[] {
				order.getStatus(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	public Map<String, String> getAgencies() throws Exception {
		final Map<String, String> result = new LinkedHashMap<String, String>();
		String sql = "select id, name from p_info where mainid=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
	        "06"
	    };
		template.query(sql, paras, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	result.put(rs.getString("id"), rs.getString("name"));
            }
        });
		return result;
	}
	
	@Override
	public Map<String, String> getLinesByAgencyId(String agencyId) throws Exception {
		final Map<String, String> result = new LinkedHashMap<String, String>();
		String sql = "select id, circuit from xj_tourism where deptid=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				agencyId
	    };
		template.query(sql, paras, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	result.put(rs.getString("id"), rs.getString("circuit"));
            }
        });
		return result;
	}
	
	private Map<String, Object> getLineInfo(String lineId) throws Exception {
		final Map<String, Object> result = new HashMap<String, Object>();
		String sql = "select circuit, price from xj_tourism where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				lineId
	    };
		template.query(sql, paras, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	result.put("lineName", rs.getString("circuit"));
            	result.put("price", rs.getDouble("price"));
            }
        });
		return result;
	}
	
}
